//
//  LoginViewController.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/1.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "LoginViewController.h"
#import "QRCodeReaderViewController.h"
#import "QRCodeReader.h"
#import "BaseNavigationController.h"
#import "SignViewController.h"
#import "QRcodeViewController.h"
#import "IQKeyboardManager.h"
#import "ZBarReaderViewController.h"
#import "SignInputViewController.h"
#import "SignForgetPdViewController.h"
#import "MenuViewController.h"
#import "ModelUser.h"
#import "UserInfoManager.h"
#import "QRCodeGenerator.h"
#import "ModelGroup.h"

#define NumberKeyBoardHeight 220
@interface LoginViewController ()<QRCodeReaderDelegate>
{
    AFHTTPRequestOperation *workingOperation;
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupView];
    [IQKeyboardManager sharedManager].enable = NO;
    if (SCREEN_HEIGHT<568) {
        self.loginHeight.constant = NumberKeyBoardHeight;
    }
//    self.pdField.returnKeyType = UIReturnKeyDefault;
//    13690699669
//    440682199110195059

//    Voluteer
//    Richard /tp  14:27:06
//    checkExistsIdNo
//    Richard /tp  14:27:11
//    checkExistsUserId
//    Richard /tp  14:28:36
//    verifyVoluteerLogin
//    findVolunteerByTelNo
//    loadVoluteer
    

}

-(void)viewWillAppear:(BOOL)animated
{
        [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDDidReceiveTouchEventNotification
                                               object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDDidReceiveTouchEventNotification object:nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.operationQueue cancelAllOperations];
}
#pragma mark 点击取消等待界面
- (void)handleNotification:(NSNotification *)notif
{
    [SVProgressHUD dismiss];
    [workingOperation cancel];
}

-(void)setupView
{
    self.pdWidth.constant = SCREEN_WIDTH/2-1;
    self.signWidth.constant = SCREEN_WIDTH/2-1;
    
    
    for (int i=11; i<13; i++) {
        UIView *view = [self.inputView viewWithTag:i];
        view.layer.borderWidth = 0.8;
        view.layer.cornerRadius = 5;
        view.layer.borderColor = [UIColor whiteColor].CGColor;
    }
    
    
    UIButton *btn = (UIButton *)[self.view viewWithTag:22];
    btn.layer.cornerRadius = 5;
    
    [self.telField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.pdField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];//修改颜色
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelEdit)];
    [self.view addGestureRecognizer:tap];
    
}
-(void)cancelEdit
{
    [self.telField resignFirstResponder];
    [self.pdField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 注册先扫描二维码
- (IBAction)SignAction:(id)sender {

//    [self pushSignViewController:@"" andGroupId:@""];
    [self showQz:SignZbarStyle];
    [self getZBarPushBlockStr:^(NSString *str) {
        
        [self checkGroupInfo:str];
    }];
//
    
}
- (IBAction)forgetAction:(id)sender
{
//    [self pushSignViewController:@"" andGroupId:@""];
    SignForgetPdViewController *signFpdVC = [[SignForgetPdViewController alloc]initWithNibName:@"SignForgetPdViewController" bundle:nil];
    BaseNavigationController *baseNC = [[BaseNavigationController alloc]initWithRootViewController:signFpdVC];
    [self presentViewController:baseNC animated:YES completion:nil];
}

-(void)checkGroupInfo:(NSString *)groupNum
{
    [SVProgressHUD showWithStatus:@"扫描中" maskType:SVProgressHUDMaskTypeBlack];
    NSDictionary *parameters = @{@"token":@"sdfsadfsadfasdf",@"module":@"VoluteerGroup",@"method":@"loadVoluteerGroupBycode",@"requestId":[NSNull new],@"requestParam":@[groupNum]};
    
    workingOperation = [Utils requestDic:parameters andRusult:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            
            NSDictionary *responseData =result[@"responseData"];
            ModelGroup *group = [ModelGroup getGroupForDic:responseData];
            if(![responseData isKindOfClass:[NSNull class]])
            {
                NSDictionary *responseData = result[@"responseData"];
                [SVProgressHUD dismiss];
                if (responseData&&responseData.allKeys.count>0) {
                    NSString *groupName = responseData[@"groupName"];
                    NSString *groupId = responseData[@"groupId"];
                    [self pushSignViewController:groupName andGroupId:groupId];
                }
            }else{
                [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
            }
            
            
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
        }
    } andError:^(id result) {
        
        
    }];
}

#pragma mark 推到注册界面
-(void)pushSignViewController:(NSString *)name andGroupId:(NSString *)groupId
{
    SignViewController *signVC = [[SignViewController alloc]initWithNibName:@"SignViewController" bundle:nil];
    [signVC setZbarStr:name];
    [signVC setZbarId:groupId];
    BaseNavigationController *baseNC = [[BaseNavigationController alloc]initWithRootViewController:signVC];
    [self presentViewController:baseNC animated:YES completion:nil];
}
#pragma mark 验证信息
-(BOOL)isInfoRight
{
    
    if (![Utils validateMobile:self.telField.text]) {
//        [Utils showAlert:@"手机号码不正确"];
        [SVProgressHUD showErrorWithStatus:@"手机号码不正确" maskType:SVProgressHUDMaskTypeBlack];
        return 0;
    }
    
    if (self.pdField.text.length<6) {
        [SVProgressHUD showErrorWithStatus:@"密码长度小于6位" maskType:SVProgressHUDMaskTypeBlack];
//        [Utils showAlert:@"密码长度小于6位"];
        return 0;
    }
    
    return 1;
}
#pragma mark 登陆
- (IBAction)LoginAction:(id)sender
{
    [SVProgressHUD showWithStatus:@"正在登陆" maskType:SVProgressHUDMaskTypeBlack];
    [self cancelEdit];
    if ([self isInfoRight]) {
        NSString *pdStr = self.pdField.text;
        NSString *pdMD5Str = [Utils md5:pdStr];
        NSDictionary *parameters = @{@"token":@"sdfsadfsadfasdf",@"module":@"Voluteer",@"method":@"verifyVoluteerLogin",@"requestId":[NSNull new],@"requestParam":@[self.telField.text,pdMD5Str]};

       workingOperation = [Utils requestDic:parameters andRusult:^(id result) {
           if ([result isKindOfClass:[NSDictionary class]]) {
               NSDictionary *responseData = result[@"responseData"];
               if ([responseData isKindOfClass:[NSDictionary class]]) {
                   NSNumber *status = responseData[@"status"];
                   if (status.intValue!=-1) {
                       ModelUser *user = [ModelUser getUserForDic:responseData];
                       [UserInfoManager sharedManager].modelMser = user;
                       [self loginFinish];
                       [SVProgressHUD dismiss];
                   }else
                   {
                       [SVProgressHUD showErrorWithStatus:@"密码错误" maskType:SVProgressHUDMaskTypeBlack];
                   }
                   
               }else
               {
                   [SVProgressHUD showErrorWithStatus:@"该手机号还没注册"];
               }
               
               
           }else
           {
               [SVProgressHUD showErrorWithStatus:@"网络错误"];
           }
        } andError:^(id result) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];

    }
    
}

-(void)loginFinish
{
    MenuViewController *menuVC = [[MenuViewController alloc]init];
//    RootNavigationController *rootNV = [[RootNavigationController alloc]initWithRootViewController:menuVC];
    [AppDelegate getInstance].menuVC= menuVC;
    [self presentViewController:menuVC animated:YES completion:nil];
}
#pragma mark - QRCodeReader Delegate Methods

- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result
{
    [self dismissViewControllerAnimated:YES completion:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"QRCodeReader" message:result delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }];
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
